import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class LocalServer {
    public static void main(String[] args) throws Exception {
        int port = 8085;//监听服务器端口
        String url = "0.0.0.0";//服务器IP地址
        Socket socket = null;
        int targetPort = 8081;//监听本地端口
        try {

            System.out.println("启动");
            /**
             * 获取输入流和输出流
             */
            while(true)
            {
                socket = new Socket(url, port);//连接服务器8085
                Socket local = new Socket("127.0.0.1",targetPort);//连接本地端口
                new Thread(new swap(socket.getInputStream(),local.getOutputStream())).start();
                new Thread(new swap(local.getInputStream(),socket.getOutputStream())).start();
                Thread.sleep(3000);
            }

//            new Thread(new swap(socket.getInputStream(),local.getOutputStream())).start();
//            new Thread(new swap(local.getInputStream(),socket.getOutputStream())).start();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null) socket.close();
        }
    }

    //读取输入流的函数
    private static class swap implements Runnable //in->out
    {
        InputStream in = null;
        OutputStream out = null;
        swap(InputStream in,OutputStream out){
            this.in = in;
            this.out = out;
        }
        @Override
        public void run() {
            int length = 0;
            byte[] buffer = new byte[1024];
            try {
                while ((length = in.read(buffer)) > -1) {
                    out.write(buffer, 0, length);
                }
            } catch (IOException e) {
                System.out.println("出错，连接关闭");
            } finally {
                System.out.println("一次传输完成");
            }
        }
    }

    private static void close(Socket socket) {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
